from django.shortcuts import render

# Create your views here.

from rest_framework.views import APIView
from . import serializers
from rest_framework.response import Response
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

'''
    生成订单链接
        用户需要登录
        用户需要提供购买的课程id
        提交为post请求
        继承APIView类    
'''

from rest_framework.permissions import IsAuthenticated

class CreatePayLinkAPIView(APIView):

    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]

    def post(self,request,*args,**kwargs):
        serializer = serializers.CreatePayLinkSerializers(data=request.data,context={'request':request})
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.pay_url)
from libs.ipay import alipay

from . import models
from utils.logging import logger
    #支付宝回调接口:公网下才能验证
class SuccessAPIView(APIView):
    def patch(self,request,*args,**kwargs):
        data = request.query_parmas.dict()
        sign = data.pop('sign')
        result = alipay.verify(data,sign)
        if result:
            pass
        return Response('同步回调完成')
    def post(self,request,*args,**kwargs):
        data = request.query_parmas.dict()  #获取支付宝的回调参数
        sign = data.pop('sign')  # 获取回调签名
        out_trada_to = data.get('out_trada_to')  #获取订单号
        result = alipay.verify(data,sign)
        if result and data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED" ):
            try:
                trade_obj = models.Order.objects.get(out_trade_no=out_trada_to)
                if trade_obj.out_trade_no != 1:
                    trade_obj.out_trade_no = 1
                    trade_obj.save()
                    logger.warning(f'{out_trada_to} 订单完成支付')
                    return Response('success')
            except:
                pass

        return Response('failed')

